//
//  YZWorkNoteVC.m
//  VET
//
//  Created by 刘文靖 on 2018/7/10.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZWorkNoteVC.h"
#import "YZWorkeNoteVM.h"
#import "YZWorkNoteListCell.h"
#import "YZCreateNoteVC.h"
#import "YZWorkNoteModel.h"
#import "YZWorkNoteLayout.h"
#import "YZWorkNoteManagePickerView.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
#import "YZRouter.h"
#import "YZRouter+AutoVC.h"
#import "YYPhotoGroupView.h"
#import "YZWorkeNoteVM.h"
#import "MJRefresh.h"
@interface YZWorkNoteVC ()<UITableViewDelegate,UITableViewDataSource,YZWorkNoteListCellDelegate>
@property (strong, nonatomic) YZWorkeNoteVM *viewModel;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIView *emptyView;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger lastPage;
@end

@implementation YZWorkNoteVC

#pragma mark - setup

- (instancetype)init
{
    self = [super init];
    if (self) {
        _tableView = [UITableView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _viewModel = [[YZWorkeNoteVM alloc] init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView.frame = self.view.bounds;
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 67, 0);
    _tableView.scrollIndicatorInsets = _tableView.contentInset;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView registerClass:[YZWorkNoteListCell class] forCellReuseIdentifier:@"YZWorkNoteListCell"];
    [self.view addSubview:_tableView];
    self.view.backgroundColor =  kColorWithHex(0xF6F7F8);
    [self setupNavigationBar];
    [self setupRefresh];
    
}
- (void)setupNavigationBar{
    self.title = @"工作笔记";
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"ico_im_more"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(createNote) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *righBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = righBarButtonItem;
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self refreshWorkNotelist];
    }];
    self.tableView.mj_header = header;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}


- (void)createNote{
    YZCreateNoteVC *createNoteVC = [[YZCreateNoteVC alloc] init];
    @weakify(self)
    createNoteVC.createNoteSuccessBlock = ^() {
        @strongify(self)
        [self refreshWorkNotelist];
    } ;
    [self.navigationController pushViewController:createNoteVC animated:YES];
}

- (void)archieveNote:(YZWorkNoteModel *)note{
    YZCreateNoteVC *createNoteVC = [[YZCreateNoteVC alloc] init];
    createNoteVC.note = note;
    @weakify(self)
    createNoteVC.createNoteSuccessBlock = ^() {
        @strongify(self)
        [self refreshWorkNotelist];
    } ;
    [self.navigationController pushViewController:createNoteVC animated:YES];
}

#pragma mark - netRequest
- (void)refreshWorkNotelist{
    @weakify(self)
    if (self.type) {//档案的笔记列表
        [self.viewModel refreshArchiveListWithType:self.type objId:self.objId completion:^(BOOL noMore) {
            @strongify(self)
            if (self.viewModel.layouts.count) {
                self.emptyView.hidden = YES;
                if (noMore) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    self.tableView.mj_footer.hidden = NO;
                    [self.tableView.mj_footer resetNoMoreData];
                }
                [self.tableView reloadData];
            }else{
                [self showEmptyView];
            }
            [self.tableView.mj_header endRefreshing];
        }error:^(NSError *error) {
            @strongify(self)
            [self.tableView.mj_header endRefreshing];
        }];
    }else{
        [self.viewModel refreshNoteListWithCompletion:^(BOOL noMore) {
            @strongify(self)
            if (self.viewModel.layouts.count) {
                self.emptyView.hidden = YES;
                if (noMore) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    self.tableView.mj_footer.hidden = NO;
                    [self.tableView.mj_footer resetNoMoreData];
                }
                [self.tableView reloadData];
            }else{
                self.tableView.mj_footer.hidden = YES;
                [self showEmptyView];
            }
            [self.tableView.mj_header endRefreshing];
        } error:^(NSError *error) {
            @strongify(self)
            [self.tableView.mj_header endRefreshing];
        }];
    }
}

- (void)loadMoreData{
    @weakify(self)
    if (self.type) {//档案的笔记列表
        [self.viewModel LoadMoreArchivesListWithType:self.type objId:self.objId completion:^(BOOL noMore) {
            @strongify(self)
            [self.tableView.mj_footer endRefreshing];
            if (noMore) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        }error:^(NSError *error) {
            @strongify(self)
            [self.tableView.mj_footer endRefreshing];
        }];
    }else{
        [self.viewModel LoadMoreNoteListWithCompletion:^(BOOL noMore) {
            @strongify(self)
            [self.tableView.mj_footer endRefreshing];
            if (noMore) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        } error:^(NSError *error) {
            @strongify(self)
            [self.tableView.mj_footer endRefreshing];
        }];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.viewModel.layouts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZWorkNoteListCell *cell= [tableView dequeueReusableCellWithIdentifier:@"YZWorkNoteListCell"];
    cell.delegate = self;
    [cell setLayout:self.viewModel.layouts[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.viewModel.layouts.count)
      return ((YZWorkNoteLayout *)self.viewModel.layouts[indexPath.row]).height;
    else
      return 0;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - YZWorkNoteListCellDelegate
- (void)cellDidClickManage:(YZWorkNoteListCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YZWorkNoteManagePickerView *pickerView = [[YZWorkNoteManagePickerView alloc] init];
    @weakify(self)
    pickerView.resultBlock = ^(NSInteger tag) {
        @strongify(self)
        YZWorkNoteModel *note = self.viewModel.noteList[indexPath.row];
        if (tag == 0){//归档
            [self archieveNote:note];
        }else if (tag == 1){//代办跟踪
            // 跳转到新建任务
            [[YZRouter sharedInstance] yz_atuoPush:@"dwNewDailyWork"];
        }else{//删除
            [self deleteNote:indexPath.row];
        }
    };
    [pickerView showWithAnimation:YES];
}

- (void)cell:(YZWorkNoteListCell *)cell didClickImageAtIndex:(NSUInteger)index{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YZWorkNoteModel *note = self.viewModel.noteList[indexPath.row];
    UIView *fromView = nil;
    NSMutableArray *items = [NSMutableArray new];
    if (note.attachType == 2) {//音频
        
        return;
    }
    for (NSUInteger i = 0; i < note.attachmentList.count; i++) {
        UIView *imgView = cell.noteView.picViews[i];
        YZAttachmentModel *attachment = note.attachmentList[i];
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.thumbView = imgView;
        if (note.attachType == 1) {
            item.videoUrl = [NSURL URLWithString:attachment.attachmentUrl];
        }

        item.largeImageURL = attachment.url;
        [items addObject:item];
        if (i == index) {
            fromView = imgView;
        }
    }
    
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:fromView toContainer:self.navigationController.view animated:YES completion:nil];
}

- (void)cellDidClickMoreButton:(YZWorkNoteListCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YZWorkNoteLayout *layout = cell.noteView.layout;
    layout.isOpening = YES;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)showEmptyView{
    self.tableView.mj_footer.hidden = YES;
    if (self.emptyView) {
        self.emptyView.hidden = NO;
    }else{
        self.emptyView = [[UIView alloc] init];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"workNote_empty"]];
        [self.emptyView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.centerX.offset(0);
        }];
        
        UILabel *topLabel = [[UILabel alloc] init];
        topLabel.text = @"工作笔记";
        topLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
        topLabel.textColor = kColorWithHex(0x434343);
        [self.emptyView addSubview:topLabel];
        [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.top.mas_equalTo(imageView.mas_bottom).offset(8);
        }];
        
        UILabel *bottomLabel = [[UILabel alloc] init];
        bottomLabel.text = @"记录日常工作中的大小事，还可进行归档整理";
        bottomLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        bottomLabel.textColor = kColorWithHex(0x9B9B9B);
        [self.emptyView addSubview:bottomLabel];
        [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.top.mas_equalTo(topLabel.mas_bottom).offset(5);
        }];
        
        UIButton *addBtn = [[UIButton alloc] init];
        [addBtn setTitle:@"添加笔记" forState:UIControlStateNormal];
        [addBtn setTitleColor:kColorWithHex(0xffffff) forState:UIControlStateNormal];
        addBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:14];
        [addBtn setBackgroundColor:kColorWithHex(0x32BE60)];
        addBtn.layer.cornerRadius = 4;
        [addBtn addTarget:self action:@selector(createNote) forControlEvents:UIControlEventTouchUpInside];
        [self.emptyView addSubview:addBtn];
        
        [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(128, 43));
            make.centerX.bottom.offset(0);
            make.top.mas_equalTo(bottomLabel.mas_bottom).offset(30);
        }];
        
        [self.view addSubview:self.emptyView];
        [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.offset(98);
        }];
    }
}

- (void)deleteNote:(NSInteger)index{
    YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
    @weakify(self)
    [customView setupUIWithTitle:nil message:@"确定要删除当前笔记?" confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
        @strongify(self)
        [self.YZ_popupController dismiss];
        YZWorkNoteModel *note = self.viewModel.noteList[index];
        [[self.viewModel deleteNote:note.noteId] subscribeError:^(NSError * _Nullable error) {
            NSLog(@"%@",error);
        } completed:^{
            [self.viewModel.noteList removeObjectAtIndex:index];
            [self.viewModel.layouts removeObjectAtIndex:index];
            [self.tableView deleteRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] withRowAnimation:UITableViewRowAnimationLeft];
            //[self.tableView reloadData];
            if (self.viewModel.layouts.count == 0) {
                [self showEmptyView];
            }
        }];
    } cancelHandler:^{
        [self.YZ_popupController dismiss];
    }];
    [self.YZ_popupController presentContentView:customView];
}

@end
